﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

using ERPStore.Extensions;
using ERPStore.Web.Extensions;

namespace ERPStore.Web.Controllers.ActionFilters
{
	/// <summary>
	/// Permet de tracker l'utilisation d'une action
	/// </summary>
	public sealed class TrackerActionFilterAttribute : ActionFilterAttribute
	{
		public TrackerActionFilterAttribute()
		{
		}

		public override void OnResultExecuted(ResultExecutedContext filterContext)
		{
			if (filterContext.HttpContext.Request["trace"] == "off")
			{
				return;
			}

			var @event = filterContext.HttpContext.CreateTrackerEvent(filterContext.Result as ViewResult);
			@event.ControllerName = filterContext.RouteData.Values["controller"] as string;
			@event.ActionName = filterContext.RouteData.Values["action"] as string;

			var viewResult = filterContext.Result as ViewResult;
			if (viewResult != null)
			{
				@event.Model = viewResult.Model;
			}

			var eventPublisher = GlobalConfiguration.Configuration.DependencyResolver.GetService<EventBrokR.IPublisher>();
			if (eventPublisher != null)
			{
				eventPublisher.PublishAsync(@event);
			}
			base.OnResultExecuted(filterContext);
		}

		public override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			base.OnActionExecuted(filterContext);
		}
	}
}
